<?php
/**
 * Created by PhpStorm.
 * User: thanatos
 * Date: 2017/11/20
 * Time: 下午4:13
 */

namespace common\models;


use Yii;
use yii\base\Model;

/**
 * Class SmsForm
 *
 * @property $code
 *
 * @package common\models
 */
class SmsForm extends Model{
    use \common\traits\Model;
    
    /** @var 手机号 */
    public $mobile;
    /** @var 发送类型 */
    public $type;
    
    /** 验证码记录前缀 */
    private $_prefix;
    /** 验证码间隔时间2分钟 */
    private $_time = 60;
    
    const TYPE_REGISTER = 1;
    
    public function rules(){
        return [
            ['mobile', 'required'],
            ['mobile', 'match', 'pattern' => Yii::$app->params['match']['mobile']],
            ['mobile', 'unique', 'targetClass' => User::className(), 'targetAttribute' => 'mobile', 'message' => '手机号已经注册'],
            ['mobile', 'validateMobile'],
            ['mobile', 'validateTime'],
            ['type', 'safe']
        ];
    }
    
    public function attributeLabels(){
        return [
            'mobile' => '手机号'
        ];
    }
    
    public function validateMobile($attribute)
    {
        if( !$this->hasErrors() ){
            if( User::find()->where(['and', ['!=', 'wechat_id', null], 'mobile' => $this->$attribute])->one() ) {
                return $this->addError('手机号已经注册');
            }
        }
    }
    
    /**
     * 验证是否在有效期内
     * @param $attribute
     */
    public function validateTime($attribute)
    {
        if( !$this->hasErrors() ){
            // 验证发送时间
            if( (Yii::$app->cache->get($this->_prefix.$this->mobile) + $this->_time) > time() && $this->type == self::TYPE_REGISTER ){
                $this->addError($attribute, '1分钟内，不能重复获取');
            }
            if( Yii::$app->cache->get('num'.$this->_prefix.$this->mobile) > 5 ){
                $this->addError($attribute, '一天不能发送超过五次');
            }
        }
    }
    
    /**
     *
     */
    public function send()
    {
        if( $this->validate() ){
            return $this->_sendSms();
        }else{
            return false;
        }
    }
    
    /**
     * TODO 等待完善
     * 发送验证码
     */
    private function _sendSms(){
        $code = $this->generateCode();
        if( YII_ENV_PROD ){
            if( Yii::$app->smser->send($this->mobile, $this->generateContent($code)) ){
                // 记录发送值
                Yii::$app->cache->set('code' . $this->getCacheKey(), $code, 3600);
                // 记录发送时间
                Yii::$app->cache->set($this->getCacheKey(), time(), 3600);
                // 记录发送次数
                $timeKey = 'num' . $this->getCacheKey();
                Yii::$app->cache->set($timeKey, Yii::$app->cache->get($timeKey) + 1, 3600 * 24);
                return true;
            }else{
                return false;
            }
        }else{
//             记录发送值
            Yii::$app->cache->set('code'. $this->getCacheKey(), $code, 3600);
            return $code;
        }
    }
    
    
    /**
     * 验证验证码有效性
     * @param string $code
     * @return bool
     */
    public function validateCode($code = '')
    {
        if( $this->validate() ){
            if( Yii::$app->cache->get('code' . $this->getCacheKey()) == $code ){
                return true;
            }
        }
        return false;
    }
    
    /**
     * 生成发送内容
     */
    private function generateContent($code)
    {
        switch($this->type) {
            case static::TYPE_REGISTER:
                return '您的验证码：'.$code.'。如非本人操作，可不用理会！【特尊医疗】';
            break;
        }
    }
    
    /**
     * 生成验证码
     * @param int $length
     * @return bool|string
     */
    private function generateCode($length = 4)
    {
        return substr(md5(uniqid(rand(), true)), -1*$length);
    }
    
    /**
     * 获取缓存的Key
     * @return string
     */
    private function getCacheKey()
    {
        return $this->_prefix.$this->mobile;
    }
    
    
}